package com.fhz.day003.room;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.fhz.day003.App;

/**
 * 时间:2022/3/22
 *
 * @author msfeng
 * 简述: TODO
 */
@Database(entities = {User.class,Student.class} ,version = 3)
public abstract class AppDatabase extends RoomDatabase {

    public abstract  UserDao userDao();

    public abstract StudentDao studentDao();

    private static AppDatabase appDatabase;

    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, "
                    + "`name` TEXT, PRIMARY KEY(`id`))");
        }
    };

    static final Migration MIGRATION_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
//            database.execSQL("ALTER TABLE Book "
//                    + " ADD COLUMN pub_year INTEGER");
        }
    };

    static final Migration MIGRATION_3_4 = new Migration(3, 4) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
//            database.execSQL("ALTER TABLE Book "
//                    + " ADD COLUMN pub_year INTEGER");
            //创建一个临时表
            //把老表的数据放入到临时表
            //创建完成以后,把临时表的数据放入到新表
            //删除老表和临时表
            //剩下带数据的新表
        }
    };


    public static AppDatabase getInstance(){
        if(appDatabase == null){
            synchronized (AppDatabase.class){
                if(appDatabase == null){
                    return   appDatabase = Room.databaseBuilder(App.context, AppDatabase.class, "info")
                            .allowMainThreadQueries()
                            .addMigrations(MIGRATION_2_3,MIGRATION_3_4)
                            .build();
                }
            }
        }
        return appDatabase;
    }


}

